<template>
    <div>
        <div>
            <van-nav-bar class="app-nav-bar" title="登录 / 注册" left-text="返回" left-arrow @click-left="$router.back()" />
        </div>

        <div>
            <van-form ref="login-form" :show-error="false" :show-error-message="false" @submit="onLogin"
                @failed="onFailed" validate-first>
                <van-field name="mobile" v-model="user.mobile" left-icon="smile-o" placeholder="请输入手机号"
                    :rules='formRules.mobile' />
                <van-field name="code" v-model="user.code" clearable left-icon="music-o" placeholder="请输入验证码"
                    :rules='formRules.code'>
                    <template #button>
                        <van-count-down v-if="isCountDownShow" @finish="isCountDownShow= false" :time="1000 *60" format="ss s" />
                        <van-button v-else size="small" round @click.prevent="onSendSms" :loading="isSendSmsLoading">发送验证码</van-button>
                    </template>
                </van-field>
                <div class="button">
                    <van-button type="info" block @click="onLogin">登录</van-button>
                </div>
            </van-form>
        </div>

    </div>
</template>
<script>
    import {
        login,
        sendSms
    } from '@/api/user'
    // import { Toast } from 'vant';
    export default {
        data() {
            return {
                user: {
                    mobile: '17090086870',
                    code: '246810'
                },
                formRules: {
                    mobile: [{
                            required: true,
                            message: '请输入手机号'
                        },
                        {
                            pattern: /^1[0-9]{10}$/,
                            message: '请输入有效的手机号码'
                        }
                    ],
                    code: [{
                            required: true,
                            message: '请输入验证码'
                        },
                        {
                            pattern: /^\d{6}$/,
                            message: '验证码格式错误'
                        }
                    ],
                },
                isCountDownShow:false, //控制倒计时状态
                isSendSmsLoading:false 
            }
        },
        methods: {
            async onLogin() {
                this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                    duration: 0
                });
                try {
                    const res = await login(this.user)
                    // console.log(res)
                    this.$toast.success('登陆成功')

                    //用vuex 存放token数据
                    this.$store.commit('setUser',res.data.data)

                    //清除lay-out缓存
                    this.$store.commit('removechePage','LayoutIndex')
                    //登录成功跳转
                    this.$router.push(this.$route.query.redirect || '/')
                } catch (err) {
                    // console.log('登陆失败', err)
                    this.$toast.fail('登陆失败')
                }
            },
            //验证失败弹窗
            onFailed(error) {
                // console.log(error);
                if (error.errors[0]) {
                    this.$toast({
                        message: error.errors[0].message,
                        position: 'top'
                    })
                }
            },
            //短信
            async onSendSms() {
                //prevent阻止默认提交
                try {
                    //前端验证
                    await this.$refs['login-form'].validate('mobile')
                    //因为后端接口有问题s所以前端验证通过就发送,嗯钮控制也是如此
                    this.isCountDownShow = true
                    this.isSendSmsLoading=true
                    //验证通过
                    const res = await sendSms(this.user.mobile)
                    console.log(res);
                    
                } catch (err) {
                    let message = ''
                    if (err && err.response && err.response.status === 429) {
                        message = '发送太频繁了,请稍后重试'
                    } else if (err.name === 'mobile') {
                        //验证失败提示
                        message = err.message
                    } else {
                        //未知错误
                        message = '发送失败，请稍后重试'
                    }
                    // console.dir(err);
                    this.$toast({
                        message,
                        position: 'top'
                    })
                }
                this.isSendSmsLoading=false
            }
        }
    }
</script>
<style lang="scss" scoped>
    .button {
        padding: 16px 26px;
    }
</style>